package com.redwine.app;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.kyleduo.switchbutton.SwitchButton;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.adapter.BannerViewPager;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.CommonListDataResponse;
import com.redwine.app.net.responses.DownOptionsBean;
import com.redwine.app.net.responses.MultipartRequest;
import com.redwine.app.net.responses.ProvinceDataResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.DimenUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.view.AlertDialog;
import com.redwine.app.view.CommonPopupListWindow;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.redwine.app.utils.Utils.showToast;

/**
 * 发布采购
 * 作者：gassion on 17/8/14 22:46
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class SendProcurementActivity extends BaseActivity {

    @ViewInject(R.id.main_banner_Layout)
    private BannerViewPager goodsBannerLayout;
    @ViewInject(R.id.view_feed_banner_inner)
    private RelativeLayout viewFeedBannerInner;
    @ViewInject(R.id.header_title)
    private TextView headerTitle;
    @ViewInject(R.id.layout_back)
    private LinearLayout layoutBack;
    private View view;
    private List<String> listPics = new ArrayList<>();//上传图片的集合
    @ViewInject(R.id.procurement_et_title)
    private EditText procurementEtTitle;
    @ViewInject(R.id.procurement_et_count)
    private EditText procurementEtCount;
    @ViewInject(R.id.procurement_et_price)
    private EditText procurementEtPrice;
    @ViewInject(R.id.procurement_tv_address)
    private TextView procurementTvAddress;
    @ViewInject(R.id.procurement_sb_invoice)
    private SwitchButton procurementSbInvoice;
    @ViewInject(R.id.procurement_sb_anonymous)
    private SwitchButton procurementSbAnonymous;
    @ViewInject(R.id.procurement_et_requirements)
    private EditText procurementEtRequirements;
    private List<DownOptionsBean> mCity = new ArrayList<>();//产地
    private String mCityID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = LayoutInflater.from(this).inflate(R.layout.activity_send_procurement, null);
        setContentView(view);
        ViewUtils.inject(this);
        initView();
        requestProvinceData();
    }

    private void initView() {
        headerTitle.setText(getString(R.string.send_procurement));
        layoutBack.setVisibility(View.VISIBLE);
        updateBanner();
    }

    @OnClick({R.id.layout_back, R.id.procurement_tv_upload_photo, R.id.procurement_tv_send, R.id.procurement_tv_address})
    public void mClick(View v) {
        switch (v.getId()) {

            case R.id.layout_back:
                finish();
                break;

            case R.id.procurement_tv_upload_photo:
                choosePhotoDialog();
                break;

            case R.id.procurement_tv_send:
                sendPublishProductData();
                break;

            case R.id.procurement_tv_address:
                showDownOptions(procurementTvAddress, mCity);
                break;

        }
    }

    /**
     * 显示下拉选项
     *
     * @param textView
     */
    private void showDownOptions(final TextView textView, final List<DownOptionsBean> stringList) {
        CommonPopupListWindow popupListWindow = new CommonPopupListWindow(this, stringList);
        popupListWindow.setOnClickListener(new CommonPopupListWindow.OnClickListener() {
            @Override
            public void onClick(int position) {
                mCityID = stringList.get(position).getId();
                textView.setText(stringList.get(position).getName());
            }
        });
        popupListWindow.showAsDropDown(textView, 0, DimenUtils.dip2px(8));
    }

    /**
     * 获取省
     */
    private void requestProvinceData() {
        if (!NetUtil.checkNet(this)) {
            showToast(R.string.generic_check);
            return;
        }
        showWaiting();
        String url = NetworkConstants.GET_PROVINCE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        GsonRequest<ProvinceDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProvinceDataResponse.class, false, params, new Response.Listener<ProvinceDataResponse>() {
            @Override
            public void onResponse(ProvinceDataResponse response) {
                dismissWaiting();
                if (response.isSuccess()) {
                    ProvinceDataResponse.DataEntity responseData = response.getData();
                    mCity = responseData.getCity();
                    procurementTvAddress.setText(mCity.get(0).getName());
                    mCityID = mCity.get(0).getId();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(R.string.generic_check);
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 发布采购
     */
    protected void sendPublishProductData() {
        final List<File> files = new ArrayList<>();
        for (int i = 0; i < listPics.size(); i++) {
            files.add(new File(listPics.get(i)));
        }

        final String title = procurementEtTitle.getText().toString();
        String num = procurementEtCount.getText().toString();
        String price = procurementEtPrice.getText().toString();
        String city = procurementTvAddress.getText().toString();
        String content = procurementEtRequirements.getText().toString();

        if (listPics.isEmpty()) {
            showToast("采购图片不能为空！");
            return;
        }

        if (TextUtils.isEmpty(title)) {
            showToast("采购标题不能为空！");
            return;
        }

        if (TextUtils.isEmpty(num)) {
            showToast("采购数量不能为空！");
            return;
        } else {
            int markVal;
            try {
                markVal = Integer.valueOf(num);
            } catch (NumberFormatException e) {
                markVal = 0;
            }
            if (markVal <= 0) {
                showToast("采购数量输入有误！");
                return;
            }
        }

        if (TextUtils.isEmpty(price)) {
            showToast("意向单价不能为空！");
            return;
        } else {
            double markVal;
            try {
                markVal = Double.parseDouble(price);
            } catch (NumberFormatException e) {
                markVal = 0;
            }
            if (markVal <= 0) {
                showToast("意向单价输入有误！");
                return;
            }
        }


        if (TextUtils.isEmpty(city)) {
            showToast("地点不能为空！");
            return;
        }
        if (TextUtils.isEmpty(content)) {
            showToast("详情描述不能为空！");
            return;
        }

        String invoice = procurementSbInvoice.isChecked() ? "1" : "2";
        String anonymous = procurementSbAnonymous.isChecked() ? "1" : "2";

        showWaiting();
        String url = NetworkConstants.PURCHASE_PRODUCT_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("title", title);
        params.put("num", num);
        params.put("price", price);
        params.put("city", mCityID);
        params.put("invoice", invoice);
        params.put("anonymous", anonymous);
        params.put("content", content);
        MultipartRequest<CommonListDataResponse> multipartRequest = new MultipartRequest<>(url, CommonListDataResponse.class, "images", files, params,
                new Response.Listener<CommonListDataResponse>() {
                    @Override
                    public void onResponse(final CommonListDataResponse response) {
                        dismissWaiting();
                        if (response.isSuccess()) {
                            EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_MAIN_DATA));
                            AlertDialog.Builder builder = new AlertDialog.Builder(SendProcurementActivity.this);
                            builder.setMessageColor(R.color.color_e82565);
                            builder.setTopImage(R.mipmap.icon_certification_success);
                            builder.setMessage(getString(R.string.send_procurement_success));
                            builder.setNegativeButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    finish();
                                }
                            });
                            builder.setPositiveButton(getString(R.string.cat), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    Intent intent = new Intent(SendProcurementActivity.this, ProcurementDetailActivity.class);
                                    intent.putExtra(PublishedSourcesDetailActivity.SHOP_NAME, title);
                                    intent.putExtra(PublishedSourcesDetailActivity.SHOP_UID, Global.user.getUid());
                                    intent.putExtra(PublishedSourcesDetailActivity.SHOP_ID, response.getData().get(0));
                                    startActivity(intent);
                                    finish();
                                }
                            });
                            AlertDialog mDialog = builder.create();
                            mDialog.setCancelable(false);
                            mDialog.show();
                        } else {
                            showToast(response.getMsg());
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(R.string.generic_check);
            }
        });
        multipartRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 60 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        APP.getInstance().getRequestQueue().add(multipartRequest);
    }

    @Override
    protected void photoCallBack(String path) {
        listPics.add(path);
        updateBanner();
    }


    /**
     * 更新banner数据显示
     */
    private void updateBanner() {
        int screenWidth = DimenUtils.getWindowsWidth(this) - DimenUtils.dip2px(16);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, screenWidth / 2);
        viewFeedBannerInner.setLayoutParams(params);
        goodsBannerLayout.setRootView(view);
        goodsBannerLayout.setVisibility(View.VISIBLE, DimenUtils.dp2px(20));
        goodsBannerLayout.setPagerAdapter(new BannerViewPager.BannerViewPagerAdapter() {
            @Override
            public int bannerImageCount() {
                return listPics.size();
            }

            @Override
            public String bannerImageUrlAtIndex(int index) {
                return listPics.get(index);
            }

            @Override
            public void bannerDidSelectAtIndex(int index) {

            }
        });
    }
}
